class Solution:
    def bagOfTokensScore(self, tokens: list, P: int) -> int:
        tokens.sort()
        res = 0
        score = 0
        for _ in range(len(tokens)):
            while tokens and P >= tokens[0]:
                P -= tokens.pop(0)
                score += 1
            res = max(score, res)
            if tokens and score > 0:
                P += tokens.pop()
                score -= 1

        return res
